package com.keyin.protocol;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import com.keyin.App;
import com.keyin.android.cache.FileDiskCache;

public class MagazineIndexCache {

	private static final String INDEX_FILE_EXT_NAME = ".idx";

	public static List<Periodical> list() {
		List<Periodical> list = new ArrayList<Periodical>();
		FileDiskCache cache = new FileDiskCache(App.root);

		List<String> names = cache.list();
		ArrayList<String> indexNames = new ArrayList<String>();
		for (int i = 0; i < names.size(); i++) {
			if (names.get(i).endsWith(INDEX_FILE_EXT_NAME)) {
				indexNames.add(names.get(i));

				String fileName = names.get(i);
				String[] array = fileName.split("\\.");

				Periodical mb = get(array[0]);
				list.add(mb);
			}
		}

		return list;
	}

	public static Periodical get(String magazineId) {
		ObjectInputStream ois = null;
		ByteArrayInputStream bis = null;
		try {
			FileDiskCache cache = new FileDiskCache(App.root);

			bis = new ByteArrayInputStream(cache.get(magazineId
					+ INDEX_FILE_EXT_NAME));
			ois = new ObjectInputStream(bis);

			return (Periodical) ois.readObject();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	public static boolean put(Periodical maga) {
		ObjectOutputStream dos = null;
		ByteArrayOutputStream baos = null;
		try {
			FileDiskCache cache = new FileDiskCache(App.root);

			baos = new ByteArrayOutputStream();
			dos = new ObjectOutputStream(baos);

			dos.writeObject(maga);

			cache.put(maga.periodical_id + INDEX_FILE_EXT_NAME,
					baos.toByteArray());

			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			if (dos != null) {
				try {
					dos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
}
